package socket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 客户端 - 带图形界面
 */
public class Client {
    private Socket socket;
    private OutputStream out;

    // GUI组件
    private JFrame frame;
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private JScrollPane scrollPane;

    public Client() {
        initializeGUI();
        connectToServer();
    }

    /**
     * 初始化图形界面
     */
    private void initializeGUI() {
        // 创建主窗口
        frame = new JFrame("聊天室客户端");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 400);
        frame.setLayout(new BorderLayout());

        // 窗口关闭事件处理
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                disconnectFromServer();
            }
        });

        // 创建聊天显示区域
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        chatArea.setWrapStyleWord(true);
        chatArea.setBackground(new Color(240, 240, 240));

        scrollPane = new JScrollPane(chatArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        // 创建底部面板（输入框和发送按钮）
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        inputField = new JTextField();
        inputField.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        sendButton = new JButton("发送");
        sendButton.setPreferredSize(new Dimension(80, 30));
        sendButton.setFont(new Font("微软雅黑", Font.BOLD, 12));
        sendButton.setBackground(new Color(70, 130, 180));
        sendButton.setForeground(Color.WHITE);

        // 添加组件到底部面板
        bottomPanel.add(inputField, BorderLayout.CENTER);
        bottomPanel.add(sendButton, BorderLayout.EAST);

        // 添加组件到主窗口
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.add(bottomPanel, BorderLayout.SOUTH);

        // 设置窗口位置居中
        frame.setLocationRelativeTo(null);

        // 添加事件监听器
        setupEventListeners();
    }

    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 发送按钮点击事件
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        // 输入框回车事件
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
    }

    /**
     * 连接到服务器
     */
    private void connectToServer() {
        try {
            appendToChatArea("正在连接服务端...");
            socket = new Socket("localhost", 8088);
            out = socket.getOutputStream();
            appendToChatArea("连接服务器成功!");

            // 启动接收消息的线程
            new Thread(new MessageReceiver()).start();

            // 显示GUI
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    frame.setVisible(true);
                    inputField.requestFocus(); // 让输入框获得焦点
                }
            });

        } catch (IOException e) {
            appendToChatArea("连接服务器失败: " + e.getMessage());
            JOptionPane.showMessageDialog(frame,
                    "无法连接到服务器: " + e.getMessage(),
                    "连接错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 发送消息
     */
    private void sendMessage() {
        String message = inputField.getText().trim();
        if (message.isEmpty()) {
            return;
        }

        if ("exit".equalsIgnoreCase(message)) {
            disconnectFromServer();
            return;
        }

        try {
            byte[] data = message.getBytes(StandardCharsets.UTF_8);
            out.write(data.length);
            out.write(data);
            out.flush();

            // 清空输入框
            inputField.setText("");

        } catch (IOException e) {
            appendToChatArea("发送消息失败: " + e.getMessage());
        }
    }

    /**
     * 从服务器断开连接
     */
    private void disconnectFromServer() {
        try {
            if (out != null) {
                // 发送退出消息
                String exitMessage = "exit";
                byte[] data = exitMessage.getBytes(StandardCharsets.UTF_8);
                out.write(data.length);
                out.write(data);
                out.flush();
            }

            if (socket != null && !socket.isClosed()) {
                socket.close();
            }

            appendToChatArea("已断开与服务器的连接");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    /**
     * 在聊天区域添加消息
     */
    private void appendToChatArea(String message) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                chatArea.append(message + "\n");
                // 自动滚动到底部
                chatArea.setCaretPosition(chatArea.getDocument().getLength());
            }
        });
    }

    /**
     * 消息接收器 - 负责从服务器接收消息
     */
    private class MessageReceiver implements Runnable {
        @Override
        public void run() {
            try (InputStream in = socket.getInputStream()) {
                byte[] buffer = new byte[1024];
                int len;

                while ((len = in.read()) != -1) {
                    if (len > 0) {
                        int bytesRead = in.read(buffer, 0, Math.min(len, buffer.length));
                        if (bytesRead > 0) {
                            String message = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                            appendToChatArea(message);
                        }
                    }
                }
            } catch (IOException e) {
                if (!socket.isClosed()) {
                    appendToChatArea("与服务器的连接已断开");
                }
            } finally {
                // 连接断开后的清理工作
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        sendButton.setEnabled(false);
                        inputField.setEnabled(false);
                        appendToChatArea("=== 连接已结束 ===");
                    }
                });
            }
        }
    }

    /**
     * 客户端开始工作的方法
     */
    public void start() {
        // GUI已经在构造函数中初始化并显示
    }

    /**
     * main方法
     */
    public static void main(String[] args) {
        // 在事件分发线程中创建GUI
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Client().start();
            }
        });
    }
}